/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.reddys.rad.inventory.controller;


import com.reddys.rad.inventory.db.ProductCategory;
import com.reddys.rad.inventory.db.Purchase;
import com.reddys.rad.inventory.db.PurchaseDetails;
import com.reddys.rad.inventory.db.PurchaseOrder;
import com.reddys.rad.inventory.db.PurchaseOrderDetails;
import com.reddys.rad.inventory.db.Stock;
import com.reddys.rad.inventory.db.StockDetails;
import com.reddys.rad.inventory.db.Vendor;
import com.reddys.rad.inventory.service.PurchaseOrderService;
import com.reddys.rad.inventory.service.PurchaseService;
import com.reddys.rad.inventory.utils.AutoCompleteList;
import com.reddys.rad.inventory.utils.EntityManagerImpl;
import com.reddys.rad.inventory.utils.Utilities;
import eu.schudt.javafx.controls.calendar.DatePicker;
import inventory.Inventory;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 * FXML Controller class
 *
 * @author REDDYS
 */
public class PurchaseController implements Initializable {

    EntityManager em = null;
    Logger log = Utilities.getLogger(PurchaseController.class.getName());
    Stage stage;
    private  ObservableList data =  FXCollections.observableArrayList();
    private  ObservableList dataList =  FXCollections.observableArrayList();
    private  ObservableList purchasedataList =  FXCollections.observableArrayList();
    @FXML
    TableView tableView;
    
    @FXML
    ComboBox vendor;
    
    @FXML
    ComboBox purchaseOrderNo;
    
    @FXML
    TextField purchaseID;
    
    @FXML
    TextField purchaseDescription;
    
    @FXML
    TextField purchaseOrderDate;
        
    @FXML
    TextField phone;
        
    @FXML
    TextField location;
    
    @FXML
    VBox vbox1;
    
    @FXML
    AnchorPane datePickerAnchorPane;
    
    DatePicker datePicker = new  DatePicker();

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
       this.stage = Inventory.stage;
       tableView.setEditable(true);
       purchaseID.setDisable(true);
        datePicker = new DatePicker(Locale.ENGLISH);
         datePicker.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
         datePicker.getCalendarView().todayButtonTextProperty().set("Today");
         datePicker.getCalendarView().setShowWeeks(false);
         datePicker.getStylesheets().add("/DatePicker.css");
         datePickerAnchorPane.getChildren().add(datePicker);
         dataList = new PurchaseOrderService().getVendorList();
         vendor.getItems().addAll(dataList);
         vendor.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
                
                     System.out.println(vendor.getSelectionModel());
                     Vendor sevendor = (Vendor) vendor.getSelectionModel().getSelectedItem();
                   
            }
        });
        purchasedataList = getPurchaseService().getPurchaseOrderList();
        purchaseOrderNo.getItems().addAll(purchasedataList);
       purchaseOrderNo.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
                if (purchaseOrderNo.getSelectionModel()!=null) {
                   PurchaseOrder purchaseOrder = (PurchaseOrder) purchaseOrderNo.getSelectionModel().getSelectedItem();
                   
                   data =  FXCollections.observableArrayList();
                   if(purchaseOrder!=null &&!Utilities.isNull(purchaseOrder.getPurchaseOrderId())){
                       System.out.println(purchaseOrder.getPurchaseOrderId());
                       purchaseOrderDate.setText(purchaseOrder.getPurchaseOrderDate()!=null?purchaseOrder.getPurchaseOrderDate().toString():"");
                       vendor.getSelectionModel().select(purchaseOrder.getVendorId());
                       ObservableList<PurchaseOrderDetails> list= FXCollections.observableArrayList();
                       list = getPurchaseService().getPurchaseOrderDetailsList(purchaseOrder.getPurchaseOrderId());
                        for(PurchaseOrderDetails purchaseOrderDetails:list){
                            ObservableList list1= FXCollections.observableArrayList();
                           list1.add(purchaseOrderDetails.getProductCategory());
                           list1.add(purchaseOrderDetails.getProductId());
                           list1.add(purchaseOrderDetails.getProductName()!=null?purchaseOrderDetails.getProductName():"");
                          list1.add("");
                          list1.add(purchaseOrderDetails.getQuantityRemaining()!=null?purchaseOrderDetails.getQuantityRemaining().toString():"0.0");
                           list1.add(purchaseOrderDetails.getUom()!=null?purchaseOrderDetails.getUom():"");
                           list1.add("");
                          list1.add("");
                          list1.add("");
                          list1.add("");
                          list1.add("");
                           data.add(list1);
                         } 
                       tableView.getItems().clear();
                        tableView.setItems(data);
                   }
                }
            }
        });
        purchaseOrderNo.setOnMouseReleased(new EventHandler() {
 
           @Override
           public void handle(Event t) {
                if (purchaseOrderNo.getSelectionModel()!=null) {
                   PurchaseOrder purchaseOrder = (PurchaseOrder) purchaseOrderNo.getSelectionModel().getSelectedItem();
                   data =  FXCollections.observableArrayList();
                   if(purchaseOrder!=null &&!Utilities.isNull(purchaseOrder.getPurchaseOrderId())){
                       System.out.println(purchaseOrder.getPurchaseOrderId());
                       ObservableList<PurchaseOrderDetails> list= FXCollections.observableArrayList();
                       list = getPurchaseService().getPurchaseOrderDetailsList(purchaseOrder.getPurchaseOrderId());
                        for(PurchaseOrderDetails purchaseOrderDetails:list){
                            ObservableList list1= FXCollections.observableArrayList();
                           list1.add(purchaseOrderDetails.getProductCategory());
                           list1.add(purchaseOrderDetails.getProductId());
                           list1.add(purchaseOrderDetails.getProductName()!=null?purchaseOrderDetails.getProductName():"");
                          list1.add("");
                          list1.add(purchaseOrderDetails.getQuantity()!=null?purchaseOrderDetails.getQuantity().toString():"0.0");
                           list1.add(purchaseOrderDetails.getUom()!=null?purchaseOrderDetails.getUom():"");
                           list1.add("");
                          list1.add("");
                          list1.add("");
                          list1.add("");
                          list1.add("");
                           data.add(list1);
                         } 
                       tableView.getItems().clear();
                        tableView.setItems(data);
                   }
                }
           }
        });
       loadTableColumns(tableView);
      // addEmptyRows();
    }    
    
        private void loadTableColumns(TableView tableView) {
   //     tableView.setEditable(true);
       TableColumn productCategory = new TableColumn("Product Category");
        productCategory.setMinWidth(100);
        Callback<TableColumn, TableCell> cellFactory =
             new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell();
                 }
             };
        
 /*       productCategory.setCellValueFactory(new Callback<CellDataFeatures<PurchaseOrderDetails, String>, String>() {

            @Override
            public String call(CellDataFeatures<PurchaseOrderDetails, String> p) {
               return p.getValue().getProductId().getProductId();
            }
  });*/
         productCategory.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(0)!=null?cdf.getValue().get(0).toString():"");
            }
           

           
        });
/*        productCategory.setOnEditCommit(
                new EventHandler<TableColumn.CellEditEvent<PurchaseOrderDetails, String>>() {
                     
                    @Override 
                    public void handle(TableColumn.CellEditEvent<PurchaseOrderDetails, String> t) {
                         System.out.println(t);
                        System.out.println("before Setting"+((PurchaseOrderDetails)t.getTableView().getItems().get(t.getTablePosition().getRow())).getProductId());
                        ((PurchaseOrderDetails)t.getTableView().getItems().get(
                                t.getTablePosition().getRow())).setProductId(t.getNewValue());
                        System.out.println("after Setting"+((PurchaseOrderDetails)t.getTableView().getItems().get(t.getTablePosition().getRow())).getProductId());
                    }
                });
 */
        TableColumn productID = new TableColumn("Product ID");
        productID.setMinWidth(100);
       productID.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(1).toString());
            }
              });
 /*       productID.setOnEditCommit(
            new EventHandler<CellEditEvent<PurchaseOrderDetails, String>>() {
                @Override
                public void handle(CellEditEvent<PurchaseOrderDetails, String> t) {
                    ((PurchaseOrderDetails) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setProductId(t.getNewValue());
                }
             }
        );
 */
        TableColumn productName = new TableColumn("Product Name");
        productName.setMinWidth(200);
        productName.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(2)!=null?cdf.getValue().get(2).toString():"");
            }  });
       // productName.setCellFactory(cellFactory);
        
        TableColumn itemCode = new TableColumn("Item Code");
        itemCode.setMinWidth(100);
        //itemCode.setCellFactory(cellFactory);
    itemCode.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(3).toString());
            }  });
        TableColumn quantity = new TableColumn("Quantity");
        quantity.setMinWidth(100);
        quantity.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Quantity");
                 }
             });
            quantity.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(4)!=null?cdf.getValue().get(4).toString():"");
            }  });
        
        TableColumn uom = new TableColumn("Uom");
        uom.setMinWidth(100);
        uom.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("UOM");
                 }
             });
            uom.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(5).toString());
            }  });
        TableColumn unitPrice = new TableColumn("Unit Price");
        unitPrice.setMinWidth(100);
        unitPrice.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("UnitPrice");
                 }
             });
            unitPrice.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(6).toString());
            }  });
        TableColumn vat = new TableColumn("VAT");
        vat.setMinWidth(100);
        vat.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("VAT");
                 }
         });
        createCellValueFactory(vat, 7);
        TableColumn discount = new TableColumn("Discount");
        discount.setMinWidth(100);

        discount.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Discount");
                 }
             });
        createCellValueFactory(discount, 8);
        TableColumn subTotal = new TableColumn("Sub Total");
        subTotal.setMinWidth(100);
        subTotal.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("SubTotal");
                 }
             });
        createCellValueFactory(subTotal,9);
        TableColumn sellingPrice = new TableColumn("Selling Price");
        sellingPrice.setMinWidth(100);
        sellingPrice.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("SellingPrice");
                 }
             });
        createCellValueFactory(sellingPrice, 10);
        tableView.getColumns().addAll(productCategory, productID, productName,itemCode, quantity, uom,unitPrice,vat, discount, subTotal,sellingPrice);
        //tableView.getItems().addAll(data);
 
    }

    private void createCellValueFactory(TableColumn tableColumn,int columnNo){
        final int columnIndex = columnNo;     
        tableColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){
             
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( 
                      cdf.getValue().get(columnIndex)!=null?cdf.getValue().get(columnIndex).toString():"");
            }
              });

    }

        public PurchaseService getPurchaseService(){
        PurchaseService purchaseService = new PurchaseService();
        return purchaseService;
    }
        
         class EditingCell extends TableCell<Object, String> {
        private String columnName ;
        private TextField textField;
        TableCell tableCell;
        public EditingCell() {
            tableCell = this;
        }
       public EditingCell(String columnName ) {
           this.columnName = columnName;
            tableCell = this;
        }
 
        @Override
        public void startEdit() {
           
                super.startEdit();
                createTextField();
                setText(null);
                setGraphic(textField);
                textField.selectAll();

        }
 
        @Override
        public void cancelEdit() {
            super.cancelEdit();
 
            setText((String) getItem());
            setGraphic(null);
        }
 
        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
 
            if (empty) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    if (textField != null) {
                        textField.setText(getString());
                    }
                    setText(null);
                    setGraphic(textField);
                } else {
                    setText(getString());
                    setGraphic(null);
                }
            }
        }
     public Property<String> inputText()
    {
        return textField.textProperty();
    }

        private void createTextField() {
            textField = new TextField(getString());
            textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
            textField.focusedProperty().addListener(new ChangeListener<Boolean>(){
                @Override
                public void changed(ObservableValue<? extends Boolean> arg0, 
                    Boolean arg1, Boolean arg2) {
                        if (!arg2) {
                            commitEdit(textField.getText());
                         ObservableList tableData = (ObservableList) tableView.getSelectionModel().getSelectedItem();
                         if(columnName.equalsIgnoreCase("Quantity")){

                        tableData.set(4, textField.getText());
                     // tc.setCellValueFactory(new PropertyValueFactory(textField.getText()));
                        tableData.set(9, calculateUnitPrice(tableData));
                         poupulateTableCellData(tableData);
 
                    }else if(columnName.equalsIgnoreCase("UOM")){
                        tableData.set(5, textField.getText());
                    }else if(columnName.equalsIgnoreCase("UnitPrice")){
                        tableData.set(6, textField.getText());
                        // tc.setCellValueFactory(new PropertyValueFactory(textField.getText()));
                        tableData.set(9, calculateUnitPrice(tableData));
                        poupulateTableCellData(tableData);
                    }else if(columnName.equalsIgnoreCase("Discount")){
                      tableData.set(8, textField.getText());
                       //tc.setCellValueFactory(new PropertyValueFactory(textField.getText()));
                      tableData.set(9, calculateUnitPrice(tableData));
                      poupulateTableCellData(tableData);
                    }else if(columnName.equalsIgnoreCase("Sub Total")){
                     tableData.set(9, textField.getText());
                    }
                    else if(columnName.equalsIgnoreCase("VAT")){
                      tableData.set(7, textField.getText());
                      // tc.setCellValueFactory(new PropertyValueFactory(textField.getText()));
                      tableData.set(9, calculateUnitPrice(tableData));
                      poupulateTableCellData(tableData);
                    }else if(columnName.equalsIgnoreCase("SellingPrice")){
                     tableData.set(10, textField.getText());
                    }
                }

               
                }
            });
             if(columnName.equalsIgnoreCase("ProductCategory")){
                System.out.println("column"+columnName);
                       ObservableList data = FXCollections.observableArrayList();
                       data = PurchaseOrderService.getProductCategoryList();
                       ArrayList list = new ArrayList();
                        for (int i = 0; i < data.size(); i++) {
                            list.add(data.get(i));
                        }
                        autoCompleteListView(list);
                       
                    }else if(columnName.equalsIgnoreCase("ProductID")){
                      ObservableList data = FXCollections.observableArrayList();
                       data = PurchaseOrderService.getProductList();
                       ArrayList list = new ArrayList();
                        for (int i = 0; i < data.size(); i++) {
                            list.add(data.get(i));
                        }
                        autoCompleteListView(list);
                       
                    }
        }
 
        public void poupulateTableCellData(ObservableList cellValueList){
            System.out.println("tableView Data -->"+cellValueList);
                  final ObservableList purchaseOrderDetailsCell = FXCollections.observableArrayList();
                         purchaseOrderDetailsCell.add(cellValueList.get(0));
                         purchaseOrderDetailsCell.add(cellValueList.get(1));
                         purchaseOrderDetailsCell.add(cellValueList.get(2));
                         purchaseOrderDetailsCell.add(cellValueList.get(3));
                         purchaseOrderDetailsCell.add(cellValueList.get(4));
                        purchaseOrderDetailsCell.add(cellValueList.get(5));
                         purchaseOrderDetailsCell.add(cellValueList.get(6));
                        purchaseOrderDetailsCell.add(cellValueList.get(7));
                        purchaseOrderDetailsCell.add(cellValueList.get(8));
                        purchaseOrderDetailsCell.add(cellValueList.get(9));
                        purchaseOrderDetailsCell.add(cellValueList.get(10));
                   System.out.println("purchaseOrderDetailsCell tableView Data -->"+purchaseOrderDetailsCell);
                     tableCell.getTableView().getItems().set(tableCell.getTableRow().getIndex(), purchaseOrderDetailsCell);

        }
        private String calculateUnitPrice(ObservableList tableData){
           String netPriceValue = "0.0";
            Double quantity = !Utilities.isNull(tableData.get(4).toString())?Double.valueOf(tableData.get(4).toString()):new Double(0.0);
            Double unitPrice = !Utilities.isNull(tableData.get(6).toString())?Double.valueOf(tableData.get(6).toString()):new Double(0.0);
            Double Vat = !Utilities.isNull(tableData.get(7).toString())?Double.valueOf(tableData.get(7).toString()):new Double(0.0);
           // Double Tax = !Utilities.isNull(tableData.get(5).toString())?Double.valueOf(tableData.get(5).toString()):new Double(0.0);
            Double Discount = !Utilities.isNull(tableData.get(8).toString())?Double.valueOf(tableData.get(8).toString()):new Double(0.0);
            Double netPrice =(quantity*unitPrice)+(Vat)-Discount;
            if(netPrice!=null){
                netPriceValue = netPrice.toString();
            }
            return netPriceValue;
        }
        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
        
        private void autoCompleteListView(ArrayList listItems){
        final AutoCompleteList<String> list = new AutoCompleteList<String>(textField);
        final List<String> allItems = listItems;

System.out.println("allItems->"+allItems);
        // filtering of list
        list.inputText().addListener(new ChangeListener<String>()
        {
            public void changed(ObservableValue<? extends String> source, String oldValue, String newValue)
            {
                list.getAvailableItems().clear();
                for (String item : allItems)
                {
                    if (item.toLowerCase().contains(newValue))
                    {
                        list.getAvailableItems().add(item);
                    }
                }
                list.getAvailableItemsSelectionModel().selectFirst();
            }
        });

        list.getChosenItems().addListener(new ListChangeListener<String>()
        {
            public void onChanged(ListChangeListener.Change<? extends String> change)
            {
                System.out.println("Your destiny consists of: ");
                for (String chosen : list.getChosenItems())
                {
                    System.out.println(" => " + chosen);
                    textField.setText(chosen);
                }
            }
        });
 
        }
           }
         
         @FXML
        public Purchase save(){
             Purchase purchase = new Purchase();
             Double totalPurchaseAmount =0.0;
            em  =EntityManagerImpl.getEntityManager();
            EntityManagerImpl.beginTransaction(em);
              try{
                  if(validateSave()){
             if(Utilities.isNull(purchaseID.getText())){

            purchase.setProductDescription(purchaseDescription.getText());
            PurchaseOrder purchaseOrder = (PurchaseOrder) purchaseOrderNo.getSelectionModel().getSelectedItem();
            purchase.setPurchaseOrderNo(purchaseOrder.getPurchaseOrderId());
            purchase.setPurchaseOrderDate(purchaseOrder.getPurchaseOrderDate());
            purchase.setPurchaseDate(datePicker.getSelectedDate());
            if(purchaseOrder!=null){
                purchase.setVendorId(purchaseOrder.getVendorId());
            }else{
            Vendor vendorEntity = (Vendor) vendor.getSelectionModel().getSelectedItem();
            purchase.setVendorId(vendorEntity.getVendorid());
            }
            ObservableList purchaseList = tableView.getItems();
            for(int i=0;i<purchaseList.size();i++){
                 ObservableList purchaseRowList = (ObservableList) purchaseList.get(i);
                 System.out.println("purchaseRowList--------->"+purchaseRowList);
                 totalPurchaseAmount = totalPurchaseAmount+Double.valueOf(!Utilities.isNull(purchaseRowList.get(9).toString())?purchaseRowList.get(9).toString():"0.0");
                 System.out.println("totalPurchaseAmount--------->"+totalPurchaseAmount);
              }
            purchase.setNetAmount(purchase.getNetAmount()!=null?purchase.getNetAmount()+totalPurchaseAmount:totalPurchaseAmount);
            purchase.setTotalAmount(purchase.getTotalAmount()!=null?purchase.getTotalAmount()+totalPurchaseAmount:totalPurchaseAmount);
            em.persist(purchase);

            for(int i=0;i<purchaseList.size();i++){
                 ObservableList purchaseRowList = (ObservableList) purchaseList.get(i);
                PurchaseDetails purchaseDetails = new PurchaseDetails();
                purchaseDetails.setPurchaseId(purchase.getPurchaseId());
                purchaseDetails.setProductId((String) purchaseRowList.get(1));
                purchaseDetails.setItemCode((String) purchaseRowList.get(3));
               // purchaseDetails.setBatchCode((String) purchaseRowList.get(1));
                purchaseDetails.setQuantity(Double.valueOf(purchaseRowList.get(4)!=null&&!purchaseRowList.get(4).toString().isEmpty()?purchaseRowList.get(4).toString():"0.0"));
               // purchaseDetails.setOrdered(Double.valueOf(purchaseRowList.get(1).toString()));
                //purchaseDetails.setQuantityReceived(Double.valueOf(purchaseRowList.get(1).toString()));
                //purchaseDetails.setQuantityAvailable(Double.valueOf(purchaseRowList.get(1).toString()));
                purchaseDetails.setUom((String) purchaseRowList.get(5));
                purchaseDetails.setVat(Double.valueOf(purchaseRowList.get(7)!=null&&!purchaseRowList.get(7).toString().isEmpty()?purchaseRowList.get(7).toString():"0.0"));
         //       purchaseDetails.setTax(Double.valueOf(purchaseRowList.get(8).toString()));
                purchaseDetails.setUnitPrice(Double.valueOf(purchaseRowList.get(6)!=null&&!purchaseRowList.get(6).toString().isEmpty()?purchaseRowList.get(6).toString():"0.0"));
                purchaseDetails.setDiscount(Double.valueOf(purchaseRowList.get(8)!=null&&!purchaseRowList.get(8).toString().isEmpty()?purchaseRowList.get(8).toString():"0.0"));
                purchaseDetails.setNetPrice(Double.valueOf(purchaseRowList.get(9)!=null&&!purchaseRowList.get(9).toString().isEmpty()?purchaseRowList.get(9).toString():"0.0"));
                purchaseDetails.setSellingPrice(Double.valueOf(purchaseRowList.get(10)!=null&&!purchaseRowList.get(10).toString().isEmpty()?purchaseRowList.get(10).toString():"0.0"));
                Query queryProductCategory = EntityManagerImpl.getEntityManager().createNamedQuery("ProductCategory.findByProductCategoryDescription");
                queryProductCategory.setParameter("productCategoryDescription", (String) purchaseRowList.get(0));
                List productCategoryList = queryProductCategory.getResultList();
                if(productCategoryList.size()>0){
                    ProductCategory productCategory = (ProductCategory) productCategoryList.get(0);
                    purchaseDetails.setProductCategoryId(productCategory.getProductCategoryId());
                }
                
                em.persist(purchaseDetails);
                 Query queryPurchaseOrderDetail = EntityManagerImpl.getEntityManager().createNamedQuery("PurchaseOrderDetails.findByPurchaseOrderIdandProductId");
                queryPurchaseOrderDetail.setParameter("purchaseOrderId", purchaseOrder.getPurchaseOrderId());
                queryPurchaseOrderDetail.setParameter("productId", purchaseDetails.getProductId());
                List purchaseDetailsList = queryPurchaseOrderDetail.getResultList();
                if(purchaseDetailsList.size()>0){
                    PurchaseOrderDetails purchaseOrderDetails = (PurchaseOrderDetails) purchaseDetailsList.get(0);
                    if(purchaseOrderDetails!=null)
                    if(!(purchaseDetails.getQuantity() >purchaseOrderDetails.getQuantityRemaining())){
                    purchaseOrderDetails.setQuantityReceived(purchaseOrderDetails.getQuantityReceived()!=null?purchaseOrderDetails.getQuantityReceived()+purchaseDetails.getQuantity():new Double("0.0")+purchaseDetails.getQuantity());
                    purchaseOrderDetails.setQuantityRemaining(purchaseOrderDetails.getQuantityRemaining()!=null&&purchaseOrderDetails.getQuantityRemaining()!=0.0?purchaseOrderDetails.getQuantityRemaining()-purchaseDetails.getQuantity():new Double("0.0"));
                    em.merge(purchaseOrderDetails);
                    }else{
                        
                        Utilities.createDialog("Please enter Correct Quantity and ensure it is less than Ordered Quantity ");
                         EntityManagerImpl.rollbackTransaction(em);
                         return null;
                    }
                }
                //totalPurchaseAmount = totalPurchaseAmount+purchaseDetails.getNetPrice();
              Stock stock = getPurchaseService().getStock(purchaseDetails.getProductId());
              if(null==stock){
                 stock = new Stock();
                 stock.setProductId(purchaseDetails.getProductId()); 
              }
                  stock.setPurchasedQuantity(stock.getPurchasedQuantity()!=null?stock.getPurchasedQuantity()+purchaseDetails.getQuantity():new Double(0.0)+purchaseDetails.getQuantity());
                  stock.setAvailableQuantity(stock.getAvailableQuantity()!=null?stock.getAvailableQuantity()+purchaseDetails.getQuantity():new Double(0.0)+purchaseDetails.getQuantity());
                  getPurchaseService().updateStock(stock,em); 


            }
                StockDetails stockDetails = new StockDetails();
                stockDetails.setStockDetailDescription(purchase.getProductDescription());
                stockDetails.setTransactionId(purchase.getPurchaseId());
                stockDetails.setTransactionDate(purchase.getPurchaseDate());
             //   stockDetails.setQuantit(purchase.get);
                stockDetails.setTransactionAmount(purchase.getTotalAmount());
                stockDetails.setTransactionType("purchase");
                em.persist(stockDetails);
                purchaseID.setText(purchase.getPurchaseId());
                EntityManagerImpl.commitTransaction(em);
                Utilities.createDialog("Transaction completed successfully");
            }
            }
            }catch(Exception e){
                e.printStackTrace();
                log.info(e.getMessage());
                EntityManagerImpl.rollbackTransaction(em);
                Utilities.createDialog("Transaction Failed");
            }
            return purchase;
        }
         
    private boolean validateSave() {
        boolean purchaseDetailsBoolean = true;
        if(Utilities.isNull(purchaseDescription.getText())){
             Utilities.createDialog("Please enter Purchase Description");
            return false;
        }
        if(null == datePicker.getSelectedDate()){
            Utilities.createDialog("Please Select Purchase Date");
            return false;
        }
        
         
        if(purchaseOrderNo.getSelectionModel()!=null){
             PurchaseOrder purchaseOrder = (PurchaseOrder) purchaseOrderNo.getSelectionModel().getSelectedItem();
            if(null == purchaseOrder){
            Utilities.createDialog("Please Select Purchase Order Number");
            return false;
            }
        }else{
             Utilities.createDialog("Please Select Purchase Order Number");
            return false;
        }
        for(int i =0;i<tableView.getItems().size();i++){
                ObservableList purchaseRowList = (ObservableList) tableView.getItems().get(i);

        if(!Utilities.isNull(purchaseRowList.get(1).toString())){
            purchaseDetailsBoolean = false;
            if(null ==purchaseRowList.get(4)) {
                Utilities.createDialog("Please enter Quantity");
                return false;
            }
            if(Utilities.isNull(purchaseRowList.get(5).toString())) {
                Utilities.createDialog("Please enter Uom");
                return false;
            }
            if(Utilities.isNull(purchaseRowList.get(6).toString())) {
                Utilities.createDialog("Please enter unit price");
                return false;
            }
            if(Utilities.isNull(purchaseRowList.get(9).toString())) {
                Utilities.createDialog("Please enter Sub Total");
                return false;
            }
        }
        }
        if(purchaseDetailsBoolean){
             Utilities.createDialog("Please Add Atleast one Product");
            return false;
        }
        System.out.println(tableView.getItems().size());
        return true;
    }


}
